package com.servlet.teacher;

import com.bean.BookBean;
import com.dao.BooksDao;
import com.dao.impl.BooksDaoImpl;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.util.JsonUtil;
import com.util.PageUtil;
import com.util.ProxyUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet("/BooksServlet2")
public class BooksServlet2 extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("4444");
        BooksDao booksDao = (BooksDao)ProxyUtil.getDaoProxy(new BooksDaoImpl());

        //queryDataBypage方法的参数currentPage肯定通过前端传递过来
        //前端如何传递参数给Servlet呢  原来我们用的是提交表单实现的表单 数据是会附加在请求的url后面  ?key=value&key=value
        //   我们只要要url后面添加?key=value就可以传值。。
        String curentPage =   req.getParameter("currentPage");
        String bookName =req.getParameter("bookName");
        String bookType =   req.getParameter("bookType");

        BookBean bookBean  = new BookBean();
        bookBean.setBook_name(bookName);
        bookBean.setType_name(bookType);//把拿到的请求参数放到JavaBean中


        JsonUtil jsonUtil = new JsonUtil();
        try {
             PageUtil<BookBean> bookBeanPageUtil =  booksDao.queryDataBypage(Integer.parseInt(curentPage),15,bookBean);

            jsonUtil.setMsg("成功");
            jsonUtil.setData(bookBeanPageUtil);


        } catch (Exception e) {
            e.printStackTrace();
            jsonUtil.setCode(1);
            jsonUtil.setMsg("系统错误:"+e.getMessage());

        }

        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson =  gsonBuilder.create();

        String jsonStr =   gson.toJson(jsonUtil);
        System.out.println("转换后的json串为:"+jsonStr);

        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();


        out.print(jsonStr);//把json字符串输出给客户端


    }
}
